package com.emmp_ard.carplate;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.emmp_ard.scan.camera.CameraManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;


public class CarPlateDetection {

    public static boolean TEST = false;
    public static String sdpath;
    public static ArrayList<String> results = new ArrayList<String>();
    public static ArrayList<IntCharPair> cps = new ArrayList<IntCharPair>();
    public final static int PRO_TIME = 10;
    public final static int CAL_TIME = 5;
    public static int counter = -1;
    public final static int RES_LENGTH = 10;
    public static int c_weight[][] = new int[PRO_TIME + 2][RES_LENGTH]; //c_weight[PRO_TIME][]作为比较权值的哨兵记录最大值
    //c_weight[PRO_TIME+1][]记录权值最大的位置
    public static int s_weight[] = new int[PRO_TIME + 2];
    //    private static final int[] indexs = new int[]{1, 2, 4, 5, 6, 7, 8};
    public static int errors = 0;



    public static String ImageProc(String path) {
        String svmpath = sdpath + "/svm.xml";
        String annpath = sdpath + "/ann.xml";
        String imgpath = path;// + "/test" + 2 + ".jpg";
        byte[] resultByte = CarPlateDetection.ImageProc(sdpath, imgpath,
                svmpath, annpath);
        String result = null;
        try {
            result = new String(resultByte, "utf-8");
            System.out.println("ImageProc:" + result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (result != null && result.length() >= RES_LENGTH) {
            File dir = new File(Environment.getExternalStorageDirectory().getPath()
                    +"/carplatedetection");
            dir.mkdir();
            File f = new File(Environment.getExternalStorageDirectory().getPath()
                    +"/carplatedetection" + "/bmp" + System.currentTimeMillis() + ".jpg");
            try {
                FileOutputStream out =  new FileOutputStream(f);
                BitmapFactory.decodeFile(imgpath).compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ProByhx(result);
//        } else if (result != null) {
//            errors++;
//            if (errors > 15) {
//                CameraManager.get().toast("抱歉,无法识别该车牌!");
//                errors = 0;
//            }
//            return null;
        } else {
            return null;
        }
    }

    private static String ProByhx(String result) {
        // TODO Auto-generated method stub


//        if (counter < CAL_TIME) {
//    	Log.w("tanglu", "counter: " + counter);

        if (counter == -1) {
            for (int i = 0; i < PRO_TIME + 2; i++) {
                for (int j = 0; j < RES_LENGTH; j++)
                    c_weight[i][j] = 0;
            }
        }

        results.add(result);
        counter++;

        for (int i = 0; i < counter; i++) {
            String temp = results.get(i);

//    		if (result.equalsIgnoreCase(temp)) {  //两次结果完全一样直接返回
//    			counter = -1;
//    			results.clear();
//    			Log.w("tanglu", "equal");
//    			return result;
//    		}

//    		for(int j=0;j<RES_LENGTH;j++){
//    			if(result.charAt(j) == temp.charAt(j)){
//    				s_weight[i]++;
//    				s_weight[counter]++;
//    			}
//    		}

            for (int j = 0; j < cps.size(); j++) {
                IntCharPair temPair = cps.get(j);
                if (temPair != null && temPair.m_char == temp.charAt(temPair.m_int)) {
                    c_weight[counter][temPair.m_int] = c_weight[counter][temPair.m_int] + 2;

                }
            }
            for (int j = 0; j < RES_LENGTH; j++) {    //否则计算相同字符的个数
                if (result.charAt(j) == temp.charAt(j)) {
                    c_weight[i][j]++;
                    c_weight[counter][j]++;
                }
            }
        }


//            return null;
//        }
//    	if(counter == CAL_TIME){
//    		for (int i = 0; i < counter; i++) {
//    			if(s_weight[i] >s_weight[PRO_TIME]){
//    				s_weight[PRO_TIME] = s_weight[i];
//    				s_weight[PRO_TIME + 1] = i;
//    			}
//    			if(s_weight[i] < s_weight[PRO_TIME]*8/10){
//
//
//    				for(int j=i;j < counter; j++){
//    					s_weight[j] = s_weight[j+1];
//    				}
//    				results.remove(i);
//    				counter--;
//    			}
//    		}  
//    	}

        if (counter < CAL_TIME - 1) {
            return null;
        }

        for (int i = 0; i < CAL_TIME; i++) {    //查找每一位权值最高的字符 
            for (int j = 0; j < RES_LENGTH; j++)
                if (c_weight[i][j] > c_weight[PRO_TIME][j]) {
                    c_weight[PRO_TIME][j] = c_weight[i][j];  //字符保存在c_weight[PRO_TIME][j]
                    c_weight[PRO_TIME + 1][j] = i;           //权值最高的字符所在字符串的位置保存在c_weight[PRO_TIME + 1][j]
                }
        }


        boolean flag = false;
        boolean ChiniseFlag = true;
        cps.clear();
        for (int i = 0; i < RES_LENGTH; i++) {            //权值低于2，将重新取样
            if (c_weight[PRO_TIME][i] < 2) {
        		if(i==3){
                    ChiniseFlag = false;
        			continue;
        		}
                flag = true;
//                counter = -1;
//                results.clear();
//                CameraManager.get().toast("识别失败，请重新扫描!");
//                return null;
            } else {
                cps.add(new IntCharPair(i, results.get(c_weight[PRO_TIME + 1][i]).charAt(i)));
            }
        }
        if (flag) {
            counter = -1;
            results.clear();
            CameraManager.get().toast("识别失败，请重新扫描!");
            return null;
        }
        char c_result[] = new char[RES_LENGTH];

        for (int i = 0; i < RES_LENGTH; i++) {
            if(i==3&&ChiniseFlag == false){
                c_result[i] = '\0';
                continue;
            }
            c_result[i] = results.get(c_weight[PRO_TIME + 1][i]).charAt(i);


        }

        counter = -1;
        results.clear();

        String ret = String.valueOf(c_result);
        return ret;

    }

//    public static String ImageProc(int[] dataList, int[] sizes) {
//        String svmpath = sdpath + "/svm.xml";
//        String annpath = sdpath + "/Fann.xml";
//        byte[] resultByte = CarPlateDetection.ImageProc(dataList, sizes, sdpath,
//                svmpath, annpath);
//        String result = null;
//        try {
//            result = new String(resultByte, "utf-8");
//            System.out.println(result);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        if (result != null && result.length() > 5) {
//            return result;
//        } else {
//            return null;
//        }
//    }

    static {
//        System.loadLibrary("gnustl_shared"); // added
//		System.loadLibrary("opencv_java");
//        System.loadLibrary("imageproc");
    }

    public static native byte[] ImageProc(String sdpath, String imgpath,
                                          String svmpath, String annpath);

    public static native byte[] ImageProc(int[] datas, int[] sizes, String sdpath,
                                          String svmpath, String annpath);

    public static native int annProc(String path);

    public static native int annProcEx(String path);


}
